package cn.knight.basic.service.impl;

import cn.knight.basic.constant.BaseConstants;
import cn.knight.basic.exception.BusinessException;
import cn.knight.basic.service.ILoginService;
import cn.knight.basic.utils.AjaxResult;
import cn.knight.basic.utils.HttpClientUtils;
import cn.knight.basic.utils.MD5Utils;
import cn.knight.basic.utils.StrUtils;
import cn.knight.basic.vo.LoginVo;

import cn.knight.user.domain.Logininfo;
import cn.knight.user.domain.User;
import cn.knight.user.domain.Wxuser;
import cn.knight.user.dto.WechatDto;
import cn.knight.user.mapper.LogininfoMapper;
import cn.knight.user.mapper.UserMapper;
import cn.knight.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxuserMapper wxuserMapper;

    /**
    * @Title: account
    * @Description: 账号登录业务
    * @Author: winnie
    * @Version: 1.0
    * @Date:  2022/7/10 19:20
    * @Parameters: [loginVo]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    public Map<String, Object> account(LoginVo loginVo) {
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String type = loginVo.getType();

        // 非空校验
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(type)){
            throw new BusinessException("参数不能为空，请重新输入");
        }

        // 根据账号&type去查询用户信息
        Logininfo logininfo = logininfoMapper.loadByAccountandType(username, type);
        if (logininfo == null){
            throw new BusinessException("账号密码错误，请重新输入");
        }
        //判断密码是否一致
        String passwordTmp = MD5Utils.encrypByMd5(logininfo.getSalt() + password);
        if (!logininfo.getPassword().equals(passwordTmp)){
            throw new BusinessException("账号密码错误，请重新输入");
        }

        // 生成UUID
        String token = UUID.randomUUID().toString();

        // 将token作为key，logininfo作为value存入redis
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

        // 将logininfo中的敏感字段置空
        logininfo.setSalt("");
        logininfo.setPassword("");

        // 将token&logininfo存入map并返回map
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }


    /**
    * @Title: wechat
    * @Description: 微信登录业务
    * @Author: winnie
    * @Version: 1.0
    * @Date:  2022/7/10 16:38
    * @Parameters: [wechatDto]
    * @Return cn.knight.basic.utils.AjaxResult
    */
    @Override
    public AjaxResult wechat(WechatDto wechatDto) {
        String code = wechatDto.getCode();
        // 非空校验
        if (StringUtils.isEmpty(code)){
            throw new BusinessException("参数不能为空，请正确输入！");
        }

        //替换链接中的数据
        String tokenUrl = BaseConstants.WechatConstant.TOKEN_URL
                .replace("APPID", BaseConstants.WechatConstant.APPID)
                .replace("SECRET", BaseConstants.WechatConstant.SECRET)
                .replace("CODE",code);

        // 调用工具类发送GET请求
        String jsonObj = HttpClientUtils.httpGet(tokenUrl);

        // 将json字符串转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(jsonObj);

        // 通过json对象，获取到access_token&openid
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");

        // 根据openId去wxuser表查询
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);

        // 判断对象是否存在&&user_id是否存在
        if (wxuser != null && wxuser.getUserId() != null){
            // 根据wxuser中的userId字段值去查询logininfo的数据
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());

            // 生成UUID
            String token = UUID.randomUUID().toString();

            // 将token作为key，logininfo作为value存入redis
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

            // 将logininfo中的敏感字段置空
            logininfo.setSalt("");
            logininfo.setPassword("");

            // 将token&logininfo存入map并返回map
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);
            return AjaxResult.me().setResultObj(map);
        }

        // 不存在，需要告诉前端,需要携带accessToken&openId
        StringBuffer sbr = new StringBuffer()
                .append("?accessToken=")
                .append(accessToken)
                .append("&openId=")
                .append(openId);
        return AjaxResult.me().setSuccess(false).setMessage("noBinder").setResultObj(sbr);
    }

    /**
    * @Title: binder
    * @Description: 微信绑定平台账号
    * @Author: winnie
    * @Version: 1.0
    * @Date:  2022/7/10 19:20
    * @Parameters: [wechatDto]
    * @Return java.util.Map<java.lang.String,java.lang.Object>
    */
    @Override
    @Transactional
    public Map<String, Object> binder(WechatDto wechatDto) {
        String phone = wechatDto.getPhone();
        String verifyCode = wechatDto.getVerifyCode();
        String openId = wechatDto.getOpenId();
        String accessToken = wechatDto.getAccessToken();

        // 非空校验
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(verifyCode)
                || StringUtils.isEmpty(openId)
                || StringUtils.isEmpty(accessToken)){
            throw new BusinessException("参数不能为空，请重新输入");
        }

        // 手机验证码校验
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_BINDER_PREFIX + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        if (phoneCodeValueRedis == null) {
            throw new BusinessException("验证码已过期，请重新获取");
        }
        String phoneValueRedis = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneValueRedis.equalsIgnoreCase(verifyCode)){
            throw new BusinessException("验证码错误，请重新输入");
        }

        // 根据手机号查询用户是否存在
        User user = userMapper.loadByPhone(phone);
        Logininfo logininfo = null;
        if (user == null){
            // 不存在，初始化user&logininfo对象并保存
            user = smsCodeDto2User(phone);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        } else {
            // 存在则查询出logininfo表信息
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }

        // 根据openId&accessToken查询微信用户的基本信息
        String wxurl= BaseConstants.WechatConstant.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxStr = HttpClientUtils.httpGet(wxurl);

        // 调用json工具方法，将json字符串转换为对应格式的对象
        Wxuser wxuser = JSONObject.parseObject(wxStr, Wxuser.class);

        // 保存wxuser数据
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        // 返回成功的map
        // 生成UUID
        String token = UUID.randomUUID().toString();

        // 将token作为key，logininfo作为value存入redis
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

        // 将logininfo中的敏感字段置空
        logininfo.setSalt("");
        logininfo.setPassword("");

        // 将token&logininfo存入map并返回map
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }

    // 初始化user对象
    private User smsCodeDto2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + "1");
        user.setPassword(saltPassword);
        user.setSalt(salt);
        // 此处最好给用户发个短信，告知他初始密码是多少
        return user;
    }


    // 拷贝logininfo对象
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

}
